<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Java线程编程指南</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: 'Noto Sans SC', Tahoma, Arial, Roboto, "Droid Sans", "Helvetica Neue", "Droid Sans Fallback", "Heiti SC", "Hiragino Sans GB", Simsun, sans-serif;
            color: #333;
            line-height: 1.6;
        }
        .hero {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .code-block {
            background-color: #2d2d2d;
            border-radius: 8px;
            color: #f8f8f2;
        }
        .method-table {
            width: 100%;
            border-collapse: collapse;
        }
        .method-table th, .method-table td {
            border: 1px solid #e2e8f0;
            padding: 12px;
            text-align: left;
        }
        .method-table tr:nth-child(even) {
            background-color: #f8fafc;
        }
        .method-table tr:hover {
            background-color: #f1f5f9;
        }
        .section-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .section-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }
        .highlight {
            background-color: #fffbdd;
            padding: 2px 4px;
            border-radius: 4px;
        }
        .footer {
            background-color: #1a202c;
            color: #e2e8f0;
        }
        .footer a:hover {
            color: #667eea;
        }
        .diagram-container {
            background-color: #f8fafc;
            border-radius: 8px;
            padding: 20px;
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Hero Section -->
    <section class="hero text-white py-20 px-4 md:px-0">
        <div class="container mx-auto max-w-5xl text-center">
            <h1 class="text-4xl md:text-5xl font-bold mb-6 font-serif">Java线程编程完全指南</h1>
            <p class="text-xl md:text-2xl mb-8 max-w-3xl mx-auto">掌握多线程编程的核心概念与最佳实践</p>
            <div class="flex justify-center space-x-4">
                <span class="px-4 py-2 bg-white bg-opacity-20 rounded-full"><i class="fas fa-code mr-2"></i>并发编程</span>
                <span class="px-4 py-2 bg-white bg-opacity-20 rounded-full"><i class="fas fa-microchip mr-2"></i>高性能</span>
                <span class="px-4 py-2 bg-white bg-opacity-20 rounded-full"><i class="fas fa-shield-alt mr-2"></i>线程安全</span>
            </div>
        </div>
    </section>

    <!-- Main Content -->
    <main class="container mx-auto max-w-5xl px-4 md:px-0 py-12">
        <!-- Introduction -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <i class="fas fa-info-circle mr-3"></i>线程基础
                </h2>
                <p class="text-lg mb-6">在Java中，<span class="highlight">Thread</span> 类是用于表示线程的基本类，它提供了丰富的方法和功能，用于管理线程的生命周期、控制线程的执行逻辑等。</p>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mt-10">
                    <div>
                        <h3 class="text-xl font-semibold mb-4 text-gray-800">线程生命周期</h3>
                        <div class="diagram-container">
                            <div class="mermaid">
                                stateDiagram-v2
                                    [*] --> NEW
                                    NEW --> RUNNABLE: start()
                                    RUNNABLE --> RUNNING: 被调度
                                    RUNNING --> BLOCKED: 等待I/O或锁
                                    BLOCKED --> RUNNABLE: I/O完成/获得锁
                                    RUNNING --> WAITING: wait()
                                    WAITING --> RUNNABLE: notify()
                                    RUNNING --> TIMED_WAITING: sleep()
                                    TIMED_WAITING --> RUNNABLE: 超时
                                    RUNNING --> TERMINATED: 执行完成
                            </div>
                        </div>
                    </div>
                    <div>
                        <h3 class="text-xl font-semibold mb-4 text-gray-800">核心概念</h3>
                        <div class="space-y-4">
                            <div class="flex items-start">
                                <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-bolt text-indigo-600"></i>
                                </div>
                                <div>
                                    <h4 class="font-medium">并发与并行</h4>
                                    <p class="text-gray-600 text-sm">并发是交替执行，并行是同时执行</p>
                                </div>
                            </div>
                            <div class="flex items-start">
                                <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-lock text-indigo-600"></i>
                                </div>
                                <div>
                                    <h4 class="font-medium">线程安全</h4>
                                    <p class="text-gray-600 text-sm">正确处理多线程共享资源</p>
                                </div>
                            </div>
                            <div class="flex items-start">
                                <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-exchange-alt text-indigo-600"></i>
                                </div>
                                <div>
                                    <h4 class="font-medium">上下文切换</h4>
                                    <p class="text-gray-600 text-sm">线程切换带来的性能开销</p>
                                </div>
                            </div>
                            <div class="flex items-start">
                                <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-tachometer-alt text-indigo-600"></i>
                                </div>
                                <div>
                                    <h4 class="font-medium">性能优化</h4>
                                    <p class="text-gray-600 text-sm">合理使用线程池减少创建开销</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 1. 创建线程 -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <span class="bg-indigo-700 text-white rounded-full w-8 h-8 flex items-center justify-center mr-3">1</span>
                    创建线程
                </h2>
                <p class="mb-6">要创建一个新的线程，可以继承 <span class="highlight">Thread</span> 类并重写其 <span class="highlight">run()</span> 方法，在 <span class="highlight">run()</span> 方法中定义线程的执行逻辑。然后通过调用 <span class="highlight">start()</span> 方法来启动线程，线程将会执行 <span class="highlight">run()</span> 方法中的逻辑。</p>
                
                <div class="code-block p-6 mb-6 overflow-x-auto">
                    <pre class="text-sm"><code class="language-java">class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread is running...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}</code></pre>
                </div>
                
                <div class="bg-blue-50 border-l-4 border-blue-400 p-4">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <i class="fas fa-lightbulb text-blue-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm text-blue-700">
                                推荐使用实现Runnable接口的方式创建线程，因为Java不支持多重继承，而实现接口可以保持继承灵活性。
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 2. 控制线程 -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <span class="bg-indigo-700 text-white rounded-full w-8 h-8 flex items-center justify-center mr-3">2</span>
                    控制线程
                </h2>
                <p class="mb-6"><span class="highlight">Thread</span> 类提供了一些方法来控制线程的执行，如 <span class="highlight">sleep()</span> 方法用于使线程休眠一段时间，<span class="highlight">yield()</span> 方法用于让出CPU执行权，<span class="highlight">join()</span> 方法用于等待线程执行结束等。</p>
                
                <div class="code-block p-6 mb-6 overflow-x-auto">
                    <pre class="text-sm"><code class="language-java">Thread.sleep(1000); // 使当前线程休眠1秒
Thread.yield();     // 让出CPU执行权
thread.join();      // 等待线程执行结束</code></pre>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mt-6">
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="font-semibold text-indigo-600 mb-2"><i class="fas fa-bed mr-2"></i>sleep()</h3>
                        <p class="text-sm text-gray-600">使线程进入TIMED_WAITING状态，不会释放锁，需要处理InterruptedException。</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="font-semibold text-indigo-600 mb-2"><i class="fas fa-hand-paper mr-2"></i>yield()</h3>
                        <p class="text-sm text-gray-600">提示调度器当前线程愿意让出CPU，但调度器可以忽略这个提示。</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="font-semibold text-indigo-600 mb-2"><i class="fas fa-hourglass-half mr-2"></i>join()</h3>
                        <p class="text-sm text-gray-600">等待目标线程终止，可设置超时时间，常用于线程间同步。</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- 3. 线程优先级 -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <span class="bg-indigo-700 text-white rounded-full w-8 h-8 flex items-center justify-center mr-3">3</span>
                    线程优先级
                </h2>
                <p class="mb-6">每个线程都有一个优先级，用于指定线程在竞争CPU执行时间时的优先级顺序。可以使用 <span class="highlight">setPriority()</span> 方法设置线程的优先级，优先级范围为1到10，其中1为最低优先级，10为最高优先级。</p>
                
                <div class="code-block p-6 mb-6 overflow-x-auto">
                    <pre class="text-sm"><code class="language-java">thread.setPriority(Thread.MAX_PRIORITY);   // 设置线程为最高优先级
thread.setPriority(Thread.MIN_PRIORITY);   // 设置线程为最低优先级</code></pre>
                </div>
                
                <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm text-yellow-700">
                                线程的优先级有三种，并非线程优先级越高就一定会执行，那个先执行由CPU调度，主方法的优先级是五。
                                不要过度依赖线程优先级，不同操作系统对优先级的实现可能有差异。
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 4. 线程状态 -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <span class="bg-indigo-700 text-white rounded-full w-8 h-8 flex items-center justify-center mr-3">4</span>
                    线程状态
                </h2>
                <p class="mb-6">线程在生命周期中会经历不同的状态，如新建状态、就绪状态、运行状态、阻塞状态和死亡状态。可以使用 <span class="highlight">getState()</span> 方法获取线程的当前状态。</p>
                
                <div class="code-block p-6 mb-6 overflow-x-auto">
                    <pre class="text-sm"><code class="language-java">Thread.State state = thread.getState();   // 获取线程的当前状态</code></pre>
                </div>
                
                <div class="mt-8">
                    <img src="https://cdn.nlark.com/yuque/0/2023/png/21449790/1692244129085-304288e6-54d3-430b-ad4f-0cdd1f0fa58f.png" alt="线程状态图" class="rounded-lg shadow-md w-full">
                </div>
            </div>
        </section>

        <!-- 5. 异常处理 -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <span class="bg-indigo-700 text-white rounded-full w-8 h-8 flex items-center justify-center mr-3">5</span>
                    异常处理
                </h2>
                <p class="mb-6">线程的执行过程中可能会抛出异常，可以使用 <span class="highlight">setUncaughtExceptionHandler()</span> 方法设置线程的异常处理器，用于捕获和处理线程抛出的异常。</p>
                
                <div class="code-block p-6 mb-6 overflow-x-auto">
                    <pre class="text-sm"><code class="language-java">thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("Thread " + t.getName() + " throws an exception: " + e.getMessage());
    }
});</code></pre>
                </div>
                
                <div class="bg-red-50 border-l-4 border-red-400 p-4">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <i class="fas fa-bug text-red-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm text-red-700">
                                线程内部的异常如果不捕获，会导致线程终止但不会影响主线程。使用未捕获异常处理器可以避免线程静默失败。
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 6. Thread的类中的常用方法 -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <span class="bg-indigo-700 text-white rounded-full w-8 h-8 flex items-center justify-center mr-3">6</span>
                    Thread的类中的常用方法
                </h2>
                
                <div class="overflow-x-auto">
                    <table class="method-table">
                        <thead>
                            <tr class="bg-gray-100">
                                <th class="font-semibold">序号</th>
                                <th class="font-semibold">方法名称</th>
                                <th class="font-semibold">类型</th>
                                <th class="font-semibold">描述</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>1</td>
                                <td>public Thread(Runnable garget)</td>
                                <td>构造</td>
                                <td>接受Runnable接口子类对象，实例化Thread对象</td>
                            </tr>
                            <tr>
                                <td>2</td>
                                <td>public Thread(Runnable taget,String name)</td>
                                <td>构造</td>
                                <td>接受Runnable接口子类对象，实例化Thread对象，并设置线程名称</td>
                            </tr>
                            <tr>
                                <td>3</td>
                                <td>public Thread(String name)</td>
                                <td>构造</td>
                                <td>实例化Thread对象，并设置线程名称</td>
                            </tr>
                            <tr>
                                <td>4</td>
                                <td>public static Thread currentThread()</td>
                                <td>普通</td>
                                <td>返回目前正在执行的线程</td>
                            </tr>
                            <tr>
                                <td>5</td>
                                <td>public final String getName()</td>
                                <td>普通</td>
                                <td>返回线程的名称</td>
                            </tr>
                            <tr>
                                <td>6</td>
                                <td>public final getPriority()</td>
                                <td>普通</td>
                                <td>返回线程的优先级</td>
                            </tr>
                            <tr>
                                <td>7</td>
                                <td><strong>public boolean isInterrupted()</strong></td>
                                <td>普通</td>
                                <td>判断目前线程时候中断，如果是，返回true，否则返回false，不会将中断清楚</td>
                            </tr>
                            <tr>
                                <td>8</td>
                                <td>public final boolean isAlice()</td>
                                <td>普通</td>
                                <td>判断线程是否存活，如果是，返回true，否则返回false</td>
                            </tr>
                            <tr>
                                <td>9</td>
                                <td>public final void join() throws Interrupted Exception</td>
                                <td>普通</td>
                                <td>等待线程死亡</td>
                            </tr>
                            <tr>
                                <td>10</td>
                                <td>public final synchronized void join(long millis)throws InterruptedException</td>
                                <td>普通</td>
                                <td>等待线程死亡</td>
                            </tr>
                            <tr>
                                <td>11</td>
                                <td>public void run()</td>
                                <td>普通</td>
                                <td>执行线程</td>
                            </tr>
                            <tr>
                                <td>12</td>
                                <td>public final void setPriority(int new Priority)</td>
                                <td>普通</td>
                                <td>设定线程名称</td>
                            </tr>
                            <tr>
                                <td>13</td>
                                <td>public final void sleep(long millis)throws InterruptedException</td>
                                <td>普通</td>
                                <td>使目前正在执行的线程休眠milllis毫秒</td>
                            </tr>
                            <tr>
                                <td>14</td>
                                <td>public vod start()</td>
                                <td>普通</td>
                                <td>开始执行线程</td>
                            </tr>
                            <tr>
                                <td>15</td>
                                <td>public void toString()</td>
                                <td>普通</td>
                                <td>返回代表线程的字符串</td>
                            </tr>
                            <tr>
                                <td>17</td>
                                <td>public static void yield()</td>
                                <td>普通</td>
                                <td>将目前正在执行的线程暂停，允许其他线程运行</td>
                            </tr>
                            <tr>
                                <td>18</td>
                                <td>public final void setDeamon(Boolean on)</td>
                                <td>普通</td>
                                <td>将一个线程设置成后台线程</td>
                            </tr>
                            <tr>
                                <td>19</td>
                                <td><strong>public void interrupt()</strong></td>
                                <td>普通</td>
                                <td>发出一个中断信号</td>
                            </tr>
                            <tr>
                                <td>20</td>
                                <td><strong>public void intrrupted()</strong></td>
                                <td>普通</td>
                                <td>判断线程是否中断，线程中断信号由给方法清楚</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

        <!-- Advanced Topics -->
        <section class="mb-16">
            <div class="bg-white rounded-xl shadow-md p-8 section-card">
                <h2 class="text-2xl font-bold mb-6 text-indigo-700 flex items-center">
                    <i class="fas fa-star mr-3"></i>进阶主题
                </h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div>
                        <h3 class="text-xl font-semibold mb-4 text-gray-800 flex items-center">
                            <i class="fas fa-shield-alt text-indigo-600 mr-2"></i>线程安全
                        </h3>
                        <p class="mb-4">多线程环境下共享数据的访问需要特别注意线程安全问题。可以使用以下机制保证线程安全：</p>
                        <ul class="list-disc pl-6 space-y-2">
                            <li>使用synchronized关键字实现互斥</li>
                            <li>使用volatile关键字保证可见性</li>
                            <li>使用java.util.concurrent包中的并发集合</li>
                            <li>使用Lock接口实现更灵活的锁控制</li>
                            <li>使用原子变量(AtomicInteger等)</li>
                        </ul>
                    </div>
                    <div>
                        <h3 class="text-xl font-semibold mb-4 text-gray-800 flex items-center">
                            <i class="fas fa-tasks text-indigo-600 mr-2"></i>线程池
                        </h3>
                        <p class="mb-4">线程池是管理线程的更好方式，可以避免频繁创建销毁线程的开销。Java提供了多种线程池实现：</p>
                        <ul class="list-disc pl-6 space-y-2">
                            <li>FixedThreadPool - 固定大小线程池</li>
                            <li>CachedThreadPool - 可缓存线程池</li>
                            <li>ScheduledThreadPool - 定时任务线程池</li>
                            <li>SingleThreadExecutor - 单线程线程池</li>
                            <li>ForkJoinPool - 分而治之线程池</li>
                        </ul>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- Footer -->
    <footer class="footer py-8">
        <div class="container mx-auto max-w-5xl px-4 md:px-0">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-lg font-medium">技术小馆</p>
                </div>
                <div>
                    <a href="http://www.yuque.com/jtostring" class="hover:text-blue-300 transition-colors">
                        <i class="fas fa-globe mr-2"></i>http://www.yuque.com/jtostring
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            mermaid.initialize({
                startOnLoad: true,
                theme: 'default',
                fontFamily: 'Noto Sans SC, sans-serif'
            });
        });
    </script>
</body>
</html>